<template>
    <div class="app-container">
        <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
        <el-form :model="queryParams" ref="queryForm" v-show="showSearch" :inline="true" label-width="100px">
            <el-row>
                <el-col :span="8">
                    <el-form-item label="脚本名称" prop="scriptNameLike">
                      <el-input
                          v-model="queryParams.scriptNameLike" placeholder="请输入执行脚本名称" clearable
                          size="default" style="width: 240px"
                          @keyup.enter="handleQuery"/>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="脚本类型" prop="scriptType">
                        <el-select
                            v-model="queryParams.scriptType" placeholder="请选择脚本类型" clearable size="default"
                            style="width: 150px"
                            @keyup.enter="handleQuery">
                            <el-option v-for="item in scriptTypes" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="!isRadio">
                    <el-form-item label="脚本状态" prop="scriptStatus">
                        <el-select
                            v-model="queryParams.scriptStatus" placeholder="请选择脚本状态" clearable size="default"
                            style="width: 160px"
                            @keyup.enter="handleQuery">
                            <el-option v-for="item in isEnableOptions" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue"/>
                        </el-select>
                    </el-form-item>
                </el-col>
                <!--        <el-col :span="6">-->
                <!--          <el-form-item label="是否启用" prop="isEnable">-->
                <!--            <el-radio-group v-model="queryParams.isEnable">-->
                <!--              <el-radio key="" label="">全部</el-radio>-->
                <!--              <el-radio v-for="dict in isEnableOptions" :key="dict.dictValue" :label="dict.dictValue">{{ dict.dictLabel }}</el-radio>-->
                <!--            </el-radio-group>-->
                <!--          </el-form-item>-->
                <!--        </el-col>-->
                <el-col :span="6">
                    <el-form-item>
                        <search-button @click="handleQuery" :perm="['data:datascript:search']"/>
                        <reset-button @click="resetQuery" :perm="['data:datascript:search']"/>
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>

        <el-row :gutter="10" class="mb8" v-if="isRadio">
            <add-button @click="handleSelect" text="确定"/>

        </el-row>

        <el-row :gutter="10" class="mb8" v-if="!isRadio">


            <add-button @click="handleAdd" :perm="['data:datascript:insert']" :roleType="['app']"/>
            <delete-button @click="handleDelete" :disabled="multiple" :perm="['data:datascript:delete']"
                           :roleType="['app']"/>
            <right-toolbar v-model:showSearch="showSearch" @query-table="getList" :perm="['data:datascript:search']"/>
        </el-row>

        <!-- 把所有字段都生成了，先删除不要的字段，再做定制化 -->
        <el-table v-loading="loading" :data="dataList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center"/>
            <!-- <el-table-column label="服务器ID" prop="id" :show-overflow-tooltip="true" min-width="100"/> -->
            <el-table-column label="脚本名称" prop="scriptName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="脚本包名" prop="scriptPackageName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="脚本类名" prop="scriptClassName" :show-overflow-tooltip="true" min-width="100"/>
            <el-table-column label="脚本类型" prop="scriptType" :show-overflow-tooltip="true" min-width="100">
                <template #default="scope">
                    {{ selectDictLabel(scriptTypes, scope.row.scriptType) }}
                </template>
            </el-table-column>
          <el-table-column label="处理模式" prop="handleMode" :show-overflow-tooltip="true" min-width="100">
            <template #default="scope">
              {{ selectDictLabel(handleModes, scope.row.handleMode) }}
            </template>
          </el-table-column>
            <el-table-column label="脚本状态" prop="isEnable" align="center" min-width="100">
                <template #default="scope">
                    {{ selectDictLabel(isEnableOptions, scope.row.scriptStatus) }}
                </template>
            </el-table-column>
            <el-table-column label="创建人" prop="createBy" align="center" width="120"/>
            <el-table-column label="创建时间" prop="createTime" align="center" width="160"/>
            <!-- <el-table-column label="更新人" prop="updateBy" align="center" width="120"/>
            <el-table-column label="更新时间" prop="updateTime" align="center" width="160"/>
            <el-table-column label="备注" prop="remark" :show-overflow-tooltip="true" min-width="100"/> -->
            <el-table-column label="操作"  align="center" width="150"
                             class-name="small-padding fixed-width"
                             v-if="hasRoleType(['app']) && !isRadio">
                <template #default="scope" >
                    <text-edit-button  @click="handleUpdate(scope.row)" :perm="['data:datascript:update']"
                                      :roleType="['app']"/>
                    <text-delete-button
                        @click="handleDelete(scope.row)" :perm="['data:datascript:delete']" :roleType="['app']"
                        :title="'是否确认删除记录'+scope.row.id+'?'"/>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>

        <!-- 新增或修改对话框 -->
        <Dialog :title="editForm.title"  :close-on-click-modal="false" v-model="editForm.open" width="800px"
                   append-to-body top="20">
            <div class="step-nlbp">
                <el-form ref="formRef" :model="editForm.data" :rules="editForm.rules">
                    <el-row>
                        <el-col :span="8">
                            <el-form-item label="脚本名称" prop="scriptName" label-width="100px">
                                <el-input v-model="editForm.data.scriptName" placeholder="请输入脚本名称" clearable/>
                        </el-form-item>
                    </el-col>
                    <el-col :span="8">
                        <el-form-item label="脚本类型" prop="scriptType" label-width="100px">
                            <el-select style="width: 145px"
                                       v-model="editForm.data.scriptType"
                                       placeholder="请选择脚本类型"
                                       class="script-select"
                                       @change="updateScriptType"
                                       clearable
                            >
                                <el-option
                                    v-for="type in scriptTypes"
                                    :key="type.dictValue"
                                    :label="type.dictLabel"
                                    :value="type.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item v-if="editForm.data.scriptType !== '4'" label="处理模式" prop="handleMode" label-width="100px">
                            <el-select style="width:145px"
                                       v-model="editForm.data.handleMode"
                                       placeholder="请选择处理模式"
                                       class="script-select"
                                       @change="updateHandleMode"
                                       clearable
                            >
                                <el-option
                                    v-for="type in handleModes"
                                    :key="type.dictValue"
                                    :label="type.dictLabel"
                                    :value="type.dictValue"
                                ></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                    <el-form-item prop="scriptContext" >
                        <span>脚本内容</span>
                            <monaco-editor v-if="editForm.open && isFlag" style="width:100%; height:700px"
                                           v-model:value="editForm.data.scriptContext"
                                           @changeTextArea="changeTextArea"
                                           ref="monacoEditor"
                                           class="script-textarea"
                                           :language="currentLanguage"
                            ></monaco-editor>
                    </el-form-item>

                </el-form>
            </div>
            <template #footer>

                <dialog-footer @ok="submitForm" @cancel="cancel" okText="暂 存">
                    <template #end>
                        <el-button type="success" @click="submitForm('publish')">发 布</el-button>
                    </template>
                </dialog-footer>

                <!--                <dialog-footer @ok="submitForm" @cancel="cancel"/>-->
            </template>
        </Dialog>
    </div>
</template>



<script>
import {search, insert, deleteByIds, updateById, selectById,getDefaultScript} from "@data/api/data/datascript";
import {debounceWrapper} from "@/utils/zmids";
import monacoEditor from './monaco-editor.vue'
import {Dialog} from '@/components/Dialog';
import {Base64} from "js-base64";

export default {
    // 此处的名字需要与菜单中Path一致，否则多Tab页切换时会刷新
    name: 'step-script',
    props: ['disabled', 'isRadio','scriptStatus'],
    components: {
        monacoEditor,
        Dialog
    },
    data() {
        return {
          isFlag:true,
            // 遮罩层
            loading: false,
            datas: [],
            // 选中数组
            ids: [],
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            dataList: [],
            // 是否发布的固定字典选项列表
            isEnableOptions: [{"dictValue": "0", "dictLabel": "未发布"}, {"dictValue": "1", "dictLabel": "发布"}],
            // 脚步类型
            scriptTypeOptions: [],
            scriptTypes: [
                {dictLabel: 'Java 语言', dictValue: '1'},
                {dictLabel: 'Groovy 语言', dictValue: '2'},
                {dictLabel: 'Python 语言', dictValue: '3'},
                {dictLabel: 'SQL脚本', dictValue: '4'}
            ],
            handleModes: [
              {dictLabel: '流模式', dictValue: '1'},
              {dictLabel: '文件模式', dictValue: '2'}
            ],
            textArea: '', // 存储脚本内容
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                // 脚本名称
                scriptName: undefined,
                // 脚本状态
                scriptStatus: '',
                // 脚本类型
                scriptType: undefined,
                // 创建人
                createByLike: '',
                // 创建时间
                createTime: undefined,
                // 更新人
                updateByLike: '',
                // 更新时间
                updateTime: undefined,
            },
            editForm: {
                // 控制 dialog
                open: false,
                // 弹出层标题
                title: '',
                // 是否修改操作
                type: 'add',
                // 表单参数
                data: {
                    // 脚本名称
                    scriptName: undefined,
                    // 脚本类型
                    scriptType: undefined,
                    // 处理模式
                    handleMode: undefined,
                    // 脚本内容
                    scriptContext: undefined,

                },
                // 规则
                rules: {
                    // 脚本名称
                    scriptName: [
                        {required: true, message: '脚本名称不可以为空', trigger: 'blur'}
                        , {min: 1, max: 128, message: "脚本名称的长度最多 128 个字符", trigger: "blur"}
                    ],
                    // 脚本类型
                    scriptType: [
                        {required: true, message: '脚本类型不可以为空', trigger: 'blur'}
                    ],
                    // 处理模式
                    handleMode: [
                      {required: true, message: '处理模式不可以为空', trigger: 'blur'}
                    ],
                    // 脚本内容
                    scriptContext: [
                        {required: true, message: '脚本内容不可以为空', trigger: 'blur'}
                    ],
                },
            }
        };
    },
    computed: {
        currentLanguage() {
            switch (this.editForm.data.scriptType) {
                case '1':
                    return 'java'
                case '2':
                    return 'groovy'
                case '3':
                    return 'python'
                default:
                    return 'java' // 默认语言
            }
        },

    },
    created() {
        // 查询列表
        this.getList();

    },
    methods: {
        handleSelect() {
            if (this.datas.length === 0) {
                this.$message.warning('请先选择要编辑的脚本')
                return
            }
            if (this.datas.length > 1) {
                this.$message.warning('只能选择一个脚本')
                return
            }
            this.$emit('selectScriptData', this.datas[0])

        },
        updateScriptType(newType) {
            if (newType === '3') {
                // 如果是Python脚本类型，弹出提示并阻止更新
                this.$message.warning('暂不支持 Python 脚本类型，请选择其他类型。')
                return
            }
            if (newType === '4') {
               this.editForm.rules.handleMode = [];
                getDefaultScript(newType,this.editForm.data.handleMode).then(response => {
                  this.editForm.data.scriptContext = Base64.decode(response.data.scriptContext);
                  this.isFlag = false;
                  setTimeout(()=>{
                    this.isFlag=true;
                  },50)
                });
                return
            }
        },
        updateHandleMode(mode) {
          getDefaultScript(this.editForm.data.scriptType,mode).then(response => {
            this.editForm.data.scriptContext = Base64.decode(response.data.scriptContext);
            this.isFlag = false;
            setTimeout(()=>{
              this.isFlag=true;
            },50)
          });
            return
        },
        changeTextArea(value) {
            console.log(value)
            this.editForm.data.scriptContext = value;
        },
        // 查询列表
        getList: debounceWrapper(function () {
          if(this.scriptStatus){
            this.queryParams.scriptStatus =this.scriptStatus;
          }
            search(this.queryParams).then(
                response => {
                    console.log('response',response)
                    this.dataList = response.data.list;
                    this.total = response.data.total;
                    this.loading = false;
                }
            );
        }),
        // 搜索按钮操作
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        // 重置按钮操作
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 表单重置
        reset() {
            this.editForm.isModify = false;
            this.editForm.data = {
                // 脚本名称
                scriptName: undefined,
                // 脚本类型
                scriptType: '',
                // 处理模式
                handleMode: '',
                // 脚本内容
                scriptContext: undefined,
                // 创建人
                createBy: '',
                // 创建时间
                createTime: undefined,
                // 更新人
                updateBy: '',
                // 更新时间
                updateTime: undefined
            };
            // 重置字段校验
            this.$refs.formRef && this.$refs.formRef.clearValidate();
            this.resetForm("formRef");
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            // 所有选中的ID
            this.ids = selection.map(item => item.id)
            this.datas = selection.map(item => {
                return {
                    id: item.id,
                    scriptName: item.scriptName,
                    scriptType: item.scriptType,
                    handleMode: item.handleMode,
                    scriptContext: item.scriptContext,
                }
            })

            // 激活多选删除
            this.multiple = !selection.length


        },
        // 新增按钮操作
        handleAdd() {
            this.reset();
            getDefaultScript(this.editForm.data.scriptType,'1').then(response => {
              this.editForm.data.scriptContext = Base64.decode(response.data.scriptContext);
              this.editForm.open = true;
              this.editForm.isModify = false;
              this.editForm.title = "新增执行脚本";
            });
        },
        // 删除按钮操作
        handleDelete: debounceWrapper(function (row) {
            const deleteIds = row ? row.id : this.ids.join(",");
            deleteByIds(deleteIds)
                .then(() => {
                    this.getList();
                    this.msgSuccess("删除成功");
                }).catch(function () {
            });
        }),
        // 修改按钮操作
        handleUpdate: debounceWrapper(function (row) {
            this.reset();
            selectById(row.id).then(response => {
                this.editForm.data = response.data;
                this.editForm.open = true;
                this.editForm.isModify = true;
                this.editForm.title = "修改执行脚本";
            });
        }),
        // 提交按钮
        submitForm: debounceWrapper(function (type) {
            this.$refs["formRef"].validate(valid => {
                if (valid) {
                    // base64 加密
                    this.editForm.data.scriptContext = Base64.encode(this.editForm.data.scriptContext);
                    const ifUpdate = this.editForm.isModify;
                    const ifPublish = type && type === 'publish';


                    if (!ifPublish) { //暂存
                        this.editForm.data['operateType'] = 'tempStore'
                    }
                    const promise = ifUpdate ? updateById(this.editForm.data) : insert(this.editForm.data);
                    this.editForm.data.scriptContext = Base64.decode(this.editForm.data.scriptContext);//解码脚本内容
                    promise.then(response => {
                        if (response.data === 1) {
                            this.msgSuccess('保存成功！');
                            this.editForm.open = false;
                            this.getList();
                        }
                    });
                }
            });
        }),
        // 取消按钮
        cancel() {
            this.editForm.open = false;
            this.reset();
        },
        //是否启用tag
        isEnableTag(isEnable) {
            //流程状态  Y启用 N禁用
            if (isEnable == 'Y') {
                return 'success'
            } else if (isEnable == 'N') {
                return 'danger'
            }
        },
    },
}
</script>

<style lang="scss" scoped>
.step-nlbp {
    display: flex;
    flex-direction: column;
    min-height: 500px;
    height: 100%;
}

.script-type-container {
    align-items: center; /* 垂直居中 */
    margin-bottom: 5px;
    //margin-top: 20px;
}

.script-type-label {
    font-size: 16px;
    margin-left: 30px; /* 与下拉框的间距 */
    font-weight: bold;
}

.script-select {
    width: 200px;
    height: 40px; /* 设置下拉框的高度 */
    font-size: 18px;

    .el-input__inner {
        height: 100%;
        padding: 10px 15px;
        border-radius: 5px;
        transition: all 0.3s ease;

        &:hover {
            border-color: #409eff; /* 鼠标悬浮时的边框颜色 */
        }
    }
}

.script-textarea {
    padding: 0px;
    width: 100%; /* 内边距 */
    font-size: 24px !important;
    border-radius: 5px; /* 边框圆角 */
    .el-input__inner {
        border: 1px solid #dcdfe6; /* 边框颜色 */
        transition: all 0.3s ease; /* 过渡效果 */
        &:hover {
            border-color: #409eff; /* 鼠标悬浮时的边框颜色 */
        }
    }
}
</style>